//package org.example.common.aspect;
//
//import cn.hutool.core.util.StrUtil;
//import cn.hutool.core.util.URLUtil;
//import cn.hutool.json.JSON;
//import cn.hutool.json.JSONObject;
//import cn.hutool.json.JSONUtil;
//import com.google.gson.Gson;
//import lombok.extern.slf4j.Slf4j;
//import org.aspectj.lang.JoinPoint;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.Signature;
//import org.aspectj.lang.annotation.*;
//import org.aspectj.lang.reflect.MethodSignature;
//import org.example.common.cache.LocalCache;
//import org.example.common.ex.GateWayException;
//import org.example.zxk.bk.mapper.BkLogMapper;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.boot.context.properties.EnableConfigurationProperties;
//import org.springframework.core.annotation.Order;
//import org.springframework.stereotype.Component;
//import org.springframework.util.AntPathMatcher;
//import org.springframework.util.ObjectUtils;
//import org.springframework.util.PathMatcher;
//import org.springframework.util.StringUtils;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import java.lang.reflect.Method;
//import java.lang.reflect.Parameter;
//import java.util.*;
//
///**
// * 统一日志处理切面
// * ignore:
// *   gateway:
// *     shouldSkipUrls
// * Created on 2018/4/26.
// */
//@Aspect
//@Component
//@Order(1)
//@Slf4j
//@EnableConfigurationProperties(value = NotAuthUrlProperties.class)
//public class WebLogAspect {
//    @Resource
//    private BkLogMapper bkLogMapper;
//    @Resource
//    private LocalCache<Map<String,String>> localCache;
//    /**
//     * 不需要用户认证的URL
//     */
//    @Resource
//    private NotAuthUrlProperties notAuthUrlProperties;
//
//    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);
//
//    @Pointcut("execution(public * org.example.*.*.controller.*.*(..))")
//    public void webLog() {
//    }
//
//    @Before("webLog()")
//    public void doBefore(JoinPoint joinPoint) throws Throwable {
//    }
//
//    @AfterReturning(value = "webLog()", returning = "ret")
//    public void doAfterReturning(Object ret) throws Throwable {
//    }
//
//    /**
//     * * 校验用户登录身份，没有登录的就返回失败
//     *      *  1:取非校验路径
//     *      *  2：满足校验要求的需要判断用户是否登录
//     * @param joinPoint
//     * @return
//     * @throws Throwable
//     */
//    @Around("webLog()")
//    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
//        Gson gson = new Gson();
//        Signature signature = joinPoint.getSignature();
//        MethodSignature methodSignature = (MethodSignature) signature;
//        Method method = methodSignature.getMethod();
//        if (!shouldSkip(request.getRequestURI())){
//            //取参数
//            gson.toJson(getParameter(method, joinPoint.getArgs()));
//            JSONObject json = new JSONObject(getParameter(method, joinPoint.getArgs()));
//            String key =(String)json.get("key");
//            String code =(String)json.get("code");
//            Map<String,String> mm =localCache.getCache(key);
//            if(ObjectUtils.isEmpty(mm)){
//                throw new GateWayException();
//            }else{
//                String codeCach = mm.get("code");
//                if(!codeCach.equals(code)){
//                    throw new GateWayException();
//                }
//            }
//        }
//        long startTime = System.currentTimeMillis();
//        //获取当前请求对象
//
//        //记录请求信息(通过Logstash传入Elasticsearch)
//        WebLog webLog = new WebLog();
//        Object result = joinPoint.proceed();
//
//        long endTime = System.currentTimeMillis();
//        String urlStr = request.getRequestURL().toString();
//        webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
//        webLog.setIp(request.getRemoteUser());
//        webLog.setMethod(request.getMethod());
//
//        webLog.setParameter(gson.toJson(getParameter(method, joinPoint.getArgs())));
//        webLog.setResult(result);
//        webLog.setSpendTime((int) (endTime - startTime));
//        webLog.setStartTime(startTime);
//        webLog.setCreateTime(new Date());
//        webLog.setUri(request.getRequestURI());
//        webLog.setUrl(request.getRequestURL().toString());
//        webLog.setLogId(UUID.randomUUID().toString().replace("-",""));
//        Map<String,Object> logMap = new HashMap<>();
//        System.out.println("request.getRequestURI()="+request.getRequestURI());
//        logMap.put("url",webLog.getUrl());
//        logMap.put("method",webLog.getMethod());
//        logMap.put("parameter",webLog.getParameter());
//        logMap.put("spendTime",webLog.getSpendTime());
//        logMap.put("description",webLog.getDescription());
//        logMap.put("ip",webLog.getIp());
//        bkLogMapper.insert(webLog);
//        LOGGER.info("{}", JSONUtil.parse(webLog));
//        //如果没有查询到缓存数据说明是没有登录
//        //排除的不需要考虑   throw new RuntimeException("测试全局异常处理中---没有权限");
//        return result;
//    }
//
//    /**
//     * 根据方法和传入的参数获取请求参数
//     */
//    private Object getParameter(Method method, Object[] args) {
//        List<Object> argList = new ArrayList<>();
//        Parameter[] parameters = method.getParameters();
//        for (int i = 0; i < parameters.length; i++) {
//            //将RequestBody注解修饰的参数作为请求参数
//            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
//            if (requestBody != null) {
//                argList.add(args[i]);
//            }
//            //将RequestParam注解修饰的参数作为请求参数
//            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
//            if (requestParam != null) {
//                Map<String, Object> map = new HashMap<>();
//                String key = parameters[i].getName();
//                if (!StringUtils.isEmpty(requestParam.value())) {
//                    key = requestParam.value();
//                }
//                map.put(key, args[i]);
//                argList.add(map);
//            }
//        }
//        if (argList.size() == 0) {
//            return null;
//        } else if (argList.size() == 1) {
//            return argList.get(0);
//        } else {
//            return argList;
//        }
//    }
//
//    /**
//     * 方法实现说明:不需要授权的路径
//     * @author:smlz
//     * @param currentUrl 当前请求路径
//     * @return:
//     * @exception:
//     * @date:2019/12/26 13:49
//     */
//    private boolean shouldSkip(String currentUrl) {
//        //路径匹配器(简介SpringMvc拦截器的匹配器)
//        //比如/oauth/** 可以匹配/oauth/token    /oauth/check_token等
//        PathMatcher pathMatcher = new AntPathMatcher();
//        for(String skipPath:notAuthUrlProperties.getShouldSkipUrls()) {
//            if(pathMatcher.match(skipPath,currentUrl)) {
//                return true;
//            }
//        }
//        return false;
//    }
//}
